import { Ref } from 'vue'
import { debounce } from 'lodash-es'

const usePreview = (
  editorRef,
  previewRef: Ref<HTMLElement | null>,
  props,
  emit
) => {
  // 左侧滚动时，右侧同步
  const getEditorScrollDom = () => {
    return editorRef.value?.getEditableContainer()?.querySelector('.w-e-scroll')
  }

  const onEditorPreviewScroll = (elm) => {
    if (previewRef.value)
      previewRef.value.scrollTop = elm.target?.scrollTop || 0
  }

  const initEditorPreviewScroll = () => {
    const editorScrollDom = getEditorScrollDom()
    editorScrollDom.addEventListener('scroll', onEditorPreviewScroll)
  }

  const removeEditorPreviewScroll = () => {
    const editorScrollDom = getEditorScrollDom()
    editorScrollDom.removeEventListener('scroll', onEditorPreviewScroll)
  }

  // 右侧滚动时，左侧同步
  const previewDomScroll = (elm) => {
    const editorScrollDom = getEditorScrollDom()
    if (editorScrollDom) editorScrollDom.scrollTop = elm.target?.scrollTop || 0
  }

  const initPreviewDomScroll = () => {
    if (!previewRef.value) return
    previewRef.value.addEventListener('scroll', previewDomScroll)
  }

  const removePreviewDomScroll = () => {
    if (!previewRef.value) return
    previewRef.value.removeEventListener('scroll', previewDomScroll)
  }

  const initOnPreview = () => {
    editorRef.value.on('onPreview', onPreview)
  }

  const preview = ref(props.isPreview === false ? false : true)

  const onChange = debounce(() => {
    const html = editorRef.value.getHtml()
    if (previewRef.value) {
      previewRef.value.innerHTML = html
    }
  }, 200)

  const onPreview = () => {
    preview.value = !preview.value
  }

  watch(
    () => props.isPreview,
    (val) => {
      if (preview.value !== val) preview.value = val
    }
  )

  watch(preview, (val) => {
    if (props.isPreview !== val) emit(val)
  })

  return {
    preview,
    onChange,
    initOnPreview,
    initEditorPreviewScroll,
    initPreviewDomScroll,
    removePreviewDomScroll,
    removeEditorPreviewScroll
  }
}

export default usePreview
